<template>
  <div class="cool-card">
    <el-row>
      <div class="search-section">
        <el-form :inline="true" :model="pagingParams">
          <el-form-item label="角色:">
            <!--<el-input size="small" v-model="searchForm.appName" placeholder="审批人"></el-input>-->
            <el-select v-model="pagingParams.role_id"
                       size="small"
                       filterable
                       placeholder="请选择一个角色"
                       @change="roleSelect"
                       ref="roleSelect"
            >
              <el-option
                v-for="item in roles"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="应用名:">
            <!--<el-input size="small" v-model="searchForm.appName" placeholder="审批人"></el-input>-->
            <el-select  v-model="pagingParams.app_name" size="small" filterable placeholder="请选择应用名称">
              <el-option
                v-for="item in appNames"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="类名:">
            <el-input size="small" v-model="pagingParams.controller_name" placeholder="输入控制器名称"></el-input>
          </el-form-item>
          <el-form-item label="匹配路径:">
            <el-input size="small" v-model="pagingParams.patterns_condition" placeholder="输入接口路径"></el-input>
          </el-form-item>
          <el-form-item label="接口描述:">
            <el-input size="small" v-model="pagingParams.memo" placeholder="请输入接口描述"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button-group>
              <el-button type="primary" size="mini" @click="onSearch">查询</el-button>
              <el-button type="primary" size="mini" @click="onClearSearchForm">刷新</el-button>
            </el-button-group>
            <el-button type="danger" size="mini" style="margin-left: 8px;" @click="onGrant" :loading="onGrantLoading">
              保存
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button size="mini" type="success" @click="onReloadAllRoleActions">重载</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-row>
    <el-row>
      <el-card>
        <el-table v-loading="loadingTable"
                  :data="actions"
                  :empty-text="'请选择一个角色后对其进行赋权'"
                  size="small"
                  ref="actionsTable"
                  row-key="id"
                  @selection-change="handleSelectionChange"
                  @select="handleSelect"
                  class="actions-table">
          <el-table-column type="selection" width="55"/>
          <el-table-column align="center" label="服务名" prop="appName" width="150"/>
          <el-table-column align="center" label="方法类型" prop="methodsCondition"/>
          <el-table-column align="center" label="类名" show-overflow-tooltip prop="controllerName"/>

          <el-table-column align="center" label="匹配路径" prop="patternsCondition">
            <template slot-scope="scope">
              <a :href="'/gateway/actions/detail?id='+scope.row.id"
                 target="_blank">{{scope.row.patternsCondition}}</a>
            </template>
          </el-table-column>
          <el-table-column align="center" label="安全级别" prop="grantLevel">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.grantLevel == 0"
                      :effect="'plain'"
                      size="mini"
                      type="danger">
                开放接口
              </el-tag>
              <el-tag v-if="scope.row.grantLevel == 1"
                      :effect="'plain'"
                      size="mini"
                      type="warning">
                需登录
              </el-tag>
              <el-tag v-if="scope.row.grantLevel == 2"
                      :effect="'plain'"
                      size="mini"
                      type="info">
                需授权
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="接口描述" show-overflow-tooltip prop="memo"/>

        </el-table>

      </el-card>

    </el-row>
    <el-row>
      <el-pagination
        class="page-section"
        background
        hide-on-single-page
        @current-change="onPaging"
        @size-change="handleSizeChange"
        layout="sizes,prev, pager, next"
        :total="pagingParams.total"/>
    </el-row>
  </div>
</template>

<script>
  import {getAllRoles} from "../../api/roles-api";
  import {getRoleActionsByQuery, grantActionsToRole} from "../../api/role-action-api";
  import {getAppNames, resetRoleActions} from "../../api/action-api";

  export default {
    name: "RoleGrant",
    data() {
      return {
        appNames: [],
        loadingTable: false,
        actions: [],
        pagingParams: {//分页查询参数
          type: 'granted',
          role_id: '',
          app_name: '',
          patterns_condition: '',
          controller_name: '',
          memo: '',
          current: 1,
          size: 10,
          orders: '!create_time',
          total: 0,//总数量
          pages: 0,//总页数

        },
        roles: [],
        selectedActions: [],
        onGrantLoading: false
      }
    },
    methods: {
      handleSelect(selection, row) {
        // console.log(selection)
        // console.log(row)
      },
      handleSelectionChange(rows) {
        this.selectedActions = rows
      },
      onGrant() {
        if (this.selectedActions.length == 0) {
          this.$message.error("请至少选择一个权限")
          return
        }
        this.actions.forEach(action => {
          action.selected = false
          this.selectedActions.some(sa => {
            if (sa.id == action.id) {
              console.log(sa.id)
              action.selected = true
            }
          })
        })
        this.onGrantLoading = true
        grantActionsToRole(this.pagingParams.role_id, this.actions).then(res => {
          this.onGrantLoading = false
          this.$message.success("保存权限成功")
          this.loadRoleActions()
        }).catch(() => {
          this.onGrantLoading = false
        });
      },
      roleSelect(val) {
        console.log(val)
        this.pagingParams.role_id = val
        this.loadRoleActions()
      },
      onSearch() {

        this.loadRoleActions();
      },
      //重载所有角色对应的权限
      onReloadAllRoleActions() {
        this.$loading()
        resetRoleActions("roles").then(res =>{
          this.$notify.success("所有角色相应的权限已重载");
          this.$loading().close()
        }).catch(()=>{
          this.$loading().close()
        })
      },
      onClearSearchForm() {
        let searchForm = {
          app_name: '',
          patterns_condition: '',
          memo: '',
          controller_name: ''
        }
        this.pagingParams = Object.assign(this.pagingParams, searchForm)
        this.loadRoleActions()
      },
      onPaging(currentPage) {
        this.pagingParams.current = currentPage
        this.loadRoleActions()
      },
      handleSizeChange(val) {
        //页大小编号
        this.pagingParams.size = val
        this.loadRoleActions()
      },
      loadAllRoles() {
        getAllRoles().then(res => {
          this.roles = res
          this.pagingParams.role_id = this.$route.query.role_id || ''
          if (this.pagingParams.role_id) {
            this.loadRoleActions();
          }
        })
      },
      //加载所有接口权限
      loadRoleActions() {
        if (this.pagingParams.role_id === '') {
          this.$message.error("请先选择一个角色")
          return
        }
        this.loadingTable = true
        getRoleActionsByQuery(this.pagingParams).then(res => {
          console.log(res)
          this.actions = res.records
          this.pagingParams.current = res.current
          this.pagingParams.pages = res.pages
          this.pagingParams.total = res.total
          this.loadingTable = false
          this.$nextTick(() => {
            this.initSelectedActions()
          })
        }).catch(() => {
          this.loadingTable = false
        })
      },
      //获取应用名字
      loadAppNames() {
        getAppNames().then(res => {
          this.appNames = res
          console.log(res)
        })
      },
      //初始化选中已选择的权限
      initSelectedActions() {
        this.actions.forEach(action => {
          if (action.selected) {
            this.$refs.actionsTable.toggleRowSelection(action, true)
          }
        })
      }
    },
    created() {
      this.loadAllRoles()
      this.loadAppNames()

    }
  }
</script>

<style scoped>
  .search-section >>> .el-form-item {
    margin-bottom: 8px;
  }

  .page-section {
    margin-top: 10px;
    float: right;
  }
</style>
